﻿using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System.IO;

public class IPABuilder {

	public static string ProjectPath = Application.dataPath + "/../proj_ios/Unity-iPhone.xcodeproj";

	public static string pbxprojPath = "\"" + Application.dataPath + "/../proj_ios/Unity-iPhone.xcodeproj/project.pbxproj" + "\"";

	public static string appPath = Application.dataPath + "/../proj_ios/build/Release-iphoneos/wqn.app ";

	public static string ipaPath =  Application.dataPath + "/../ProductName";

	public static string rawIPAFilePath = Application.dataPath + "/../ProductName/Unity-iPhone.ipa";

    public static string targetIPAFilePath = Application.dataPath + "/../ProductName/nProductName.ipa";

	public static string CodeSing = "\"iPhone Distribution: shanghai Giant Tongping Network Technology Co., Ltd.\"";

	public static string provision =   Application.dataPath + "/../AppendFile/wqnInHouse.mobileprovision";

	public static string provision_uuid = "5eba93de-0a6b-4ad5-b96f-638c30e24dd9";

	public static string temp_id = "6K2V46G7ZP";


	public static string archivePath = Application.dataPath + "/../proj_ios/wqn.xcarchive";

	public static string exportOptionsPlist = Application.dataPath + "/../AppendFile/exportEnterprise.plist";

	// Use this for initialization

	public static void buildIPA(){
	

		UnityEngine.Debug.Log ("Start !!!!!");

		if (!clearBuild ()) {
			UnityEngine.Debug.LogError (" clear build error");
			return;
		}
			
		if (!setProvisioningStyle ()) {
			UnityEngine.Debug.LogError (" set ProvisioningStyle error");
			return;
		}

		if (!buildAPP ()) {
			UnityEngine.Debug.LogError (" build app error");
			return;
		}

		if (!generateIPA ()) {
			UnityEngine.Debug.LogError (" generate ipa error");
			return;
		}

		if(!RenameIPAFile())
		{
			UnityEngine.Debug.LogError("Rename IPA File Error");
			return;
		}

		UnityEngine.Debug.Log("Xcode Build Success");
	}

	public static bool clearBuild(){

		string args = " -verbose " + " -project " + ProjectPath + " -target " + " Unity-iPhone " + " -configuration " + " Release " + " clean";

		UnityEngine.Debug.Log (args); 

		return startProcess ("xcodebuild",args);
	}

	public static bool setProvisioningStyle(){

		string args = "-i "+ "\"" + "\"" + "\""+" s%\\ProvisioningStyle.*%\\ProvisioningStyle = Manual;SystemCapabilities = { com.apple.Push={enabled=1;};com.apple.BackgroundModes={enabled = 1;};};%g "+"\"" + pbxprojPath;
		
		UnityEngine.Debug.Log (args);
		
		return startProcess ("sed",args);
	}

	public static bool buildAPP(){

		string signArgs = " CODE_SIGN_IDENTITY=" + CodeSing
						  + " PROVISIONING_PROFILE=" + provision_uuid
						  + " DEVELOPMENT_TEAM=" + temp_id;
		string args =  " archive" + " -verbose" + " -project " + ProjectPath +" -scheme Unity-iPhone " + " -archivePath "+ archivePath + " -configuration "+" Release "+" -jobs 8"+  signArgs;


		UnityEngine.Debug.Log (args);



		return startProcess ("xcodebuild",args);
	}

	public static bool generateIPA(){

		DirectoryInfo ipaPathFolder = Directory.GetParent (ipaPath);
		if (!ipaPathFolder.Exists) {
			UnityEngine.Debug.Log ("Create Folder " + ipaPathFolder);
			ipaPathFolder.Create ();
		}

		string args = " -verbose -exportArchive " + " -archivePath " + archivePath + " -exportOptionsPlist " + exportOptionsPlist + " -exportPath " + ipaPath;

		UnityEngine.Debug.Log ("xcodebuild" + args);

		return startProcess ("xcodebuild",args);

	}

//	public static bool generateIPA(){
//	
//		string args =  " -sdk iphoneos PackageApplication -v " + appPath + " -o " + ipaPath + " --sign " + CodeSing + " --embed " + provision;
//		
//		UnityEngine.Debug.Log (args);
//
//		return startProcess ("xcrun",args);
//
//	}

	public static bool RenameIPAFile()
	{
		if(!File.Exists(rawIPAFilePath))
		{
			UnityEngine.Debug.Log("RenameIPAFile Error: " + rawIPAFilePath + " not exist");
			return false;
		}

		if(File.Exists(targetIPAFilePath))
		{
			File.Delete(targetIPAFilePath);
		}

		UnityEngine.Debug.Log("mv " + rawIPAFilePath + " " + targetIPAFilePath);
		File.Move(rawIPAFilePath, targetIPAFilePath);

		return true;
	}

	public static void testW(){
	

		string cmd = Application.dataPath + "/../a.sh";

		UnityEngine.Debug.Log (cmd);

		startProcess (cmd,"1111");

	}



	public static bool startProcess(string cmd, string args){

		try  
		{  
			Process process = new Process();  
			 
			ProcessStartInfo startInfo = new ProcessStartInfo(cmd, args);  

			process.StartInfo = startInfo;  


			process.StartInfo.UseShellExecute = false;

			process.StartInfo.RedirectStandardError = true;
			process.StartInfo.RedirectStandardOutput = true;

			process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; 

			process.Start();  

			System.IO.StreamReader output = process.StandardOutput;
			
			System.IO.StreamReader err = process.StandardError;

			string outputString = output.ReadToEnd();
			
			string errString = err.ReadToEnd();

			process.WaitForExit();  

			UnityEngine.Debug.Log(outputString);

			if(errString != null && errString.Length != 0)
				UnityEngine.Debug.LogError(errString);

			output.Close();

			err.Close();

			process.Close();  
		}  
		catch (System.Exception e)  
		{  
			UnityEngine.Debug.Log(e);  

			return false;
		}  

		return true;

	}


}